package TMS.src;

import java.util.*;

public class Shop {
    public static int numOfShop = 0;
    private String shopName;
    private String shopId;
    private boolean shopStatus;
    private User master;
    //商店存储的所有商品
    private Map<String, Commodity> commodities = new HashMap<>();//commodityId+commodity

    public Shop() {
    }

    public Shop(String shopName) {
        numOfShop++;
        this.shopName = shopName;
        this.setShopStatus(true);
    }

    String getShopName() {
        return shopName;
    }

    void setShopName(String shopName) {
        this.shopName = shopName;
    }

    String getShopId() {
        return shopId;
    }

    void setShopId(int id) {
        this.shopId = this.shopId = "S-" + id;
        ;
    }

    boolean getShopStatus() {
        return this.shopStatus;
    }

    void setShopStatus(boolean shopStatus) {
        this.shopStatus = shopStatus;
    }

    int getNumOfShop() {
        return numOfShop;
    }

    void setMaster(User master) {
        this.master = master;
    }

    User getMaster() {
        return this.master;
    }

    Map getCommodities() {
        return this.commodities;
    }

    // 排序的方法（返回值为HashMap的子类LinkedHashMap； 原因：HashMap无序；LinkedHashMap有序）
    Map<String, Shop> sortListShop(Map<String, Shop> map) {
        //HashMap无序；LinkedHashMap有序）
        LinkedHashMap<String, Shop> linkedHashMap = new LinkedHashMap<>();
        Set<Map.Entry<String, Shop>> entrySet = map.entrySet();
        List<Map.Entry<String, Shop>> list = new ArrayList<>(entrySet);
        list.sort(Comparator.comparingInt(o -> Integer.parseInt(o.getValue().getShopId().substring(2))));
        list.forEach(item -> linkedHashMap.put(item.getKey(), item.getValue()));
        return linkedHashMap;
    }

    String RegisterShop(String[] cmd) {
        User current_user = Const.current_user;
        if (cmd.length != 2)
            return "Illegal argument count";
        if (current_user == null)
            return "Please log in first";
        String shopName = cmd[1];
        String identity = current_user != null ? current_user.getIdentity() : null;
        boolean identity_illegal = identity != null ? !identity.equals("Merchant") : false;
        boolean no_place = false;
        boolean shop_name_illegal = !shopName.matches("^[A-Za-z][A-Za-z_-]{0,49}$");
        boolean shop_name_exists = false;
        if (Const.masterShop_existed != null) {
            if (Const.masterShop_existed.get(current_user.getCard_number()) != null) {
                if (Const.masterShop_existed.get(current_user.getCard_number()).size() >= 5)
                    no_place = true;
            }
        }
        if (!Const.masterShop_existed.isEmpty()) //shop_name_exists
            if (Const.masterShop_existed.get(current_user.getCard_number()) != null)
                for (Shop value : Const.masterShop_existed.get(current_user.getCard_number()).values()) {
                    if (shopName.equals(value.getShopName())) {
                        shop_name_exists = true;
                    }
                }

        if (identity_illegal) {
            return "Permission denied";
        } else if (no_place) {
            return "Shop count reached limit";
        } else if (shop_name_illegal) {
            return "Illegal shop name";
        } else if (shop_name_exists) {
            return "Shop name already exists";
        } else {
            Shop shop = new Shop(shopName);
            shop.setMaster(current_user);
            shop.setShopId(shop.getNumOfShop());
            Const.allShop_existed.put(shop.getShopId(), shop);

            if (Const.masterShop_existed.containsKey(current_user.getCard_number()))
                Const.masterShop_existed.get(current_user.getCard_number()).put(shop.getShopId(), shop);
            else {
                HashMap<String, Shop> newMap = new HashMap<String, Shop>();
                newMap.put(shop.getShopId(), shop);
                Const.masterShop_existed.put(current_user.getCard_number(), newMap);
            }
            return "Register shop success (shopId: " + shop.shopId + ")";
        }
    }

    String ListShop(String[] cmd) {
        User current_user = Const.current_user;
        String identity = current_user != null ? current_user.getIdentity() : null;
        if (cmd.length > 2)
            return "Illegal argument count";
        if (current_user == null)
            return "Please log in first";

        if (cmd.length == 1) {//无参数
            if (current_user.getIdentity().equals("Customer")) {//用户查看所有店铺
                if (Const.allShop_existed.isEmpty())
                    return "Shop not exists";

                Map<String, Shop> sortedShop = sortListShop(Const.allShop_existed);
                for (Shop shop : sortedShop.values()) {
                    System.out.println(shop.getShopId() + " " + shop.getShopName());
                }
            } else if (current_user.getIdentity().equals("Merchant")) {//商家查看自己的所有店铺
                if (Const.masterShop_existed.containsKey(current_user.getCard_number())) {
                    if (!Const.masterShop_existed.get(current_user.getCard_number()).isEmpty()) {
                        Map<String, Shop> sortedShop = sortListShop(Const.masterShop_existed.get(current_user.getCard_number()));
                        for (Shop shop : sortedShop.values()) {
                            System.out.println(shop.getShopId() + " " + shop.getShopName());
                        }
                    }
                } else
                    return "Shop not exists";
            } else if (current_user.getIdentity().equals("Administrator")) {//管理员查看所有店铺
                if (Const.allShop_existed.isEmpty())
                    return "Shop not exists";

                Map<String, Shop> sortedShop = sortListShop(Const.allShop_existed);
                for (Shop shop : sortedShop.values()) {
                    System.out.println(shop.getMaster().getCard_number() + " " + shop.getShopId() + " " + shop.getShopName());
                }
            }
        } else if (cmd.length == 2) {//有参数
            String cardNumber = cmd[1];
            boolean permission_illegal = !current_user.getIdentity().equals("Administrator");
            boolean cardNumber_illegal = Gadget.check_user_card_illegal(cardNumber);//!cardNumber.matches("^([0-3]\\d{3}|4[0-4]\\d{2}|4500)(178[5-9]|179\\d|18[0-7]\\d|188[0-6])([1-2]\\d{3}|3000)$");
            boolean cardNumber_not_existed = !Const.user_existed.containsKey(cardNumber);
            boolean cardNumber_not_merchant = true;
            boolean cardNumber_no_shop = true;

            if (!cardNumber_not_existed)
                if (Const.user_existed.get(cardNumber).getIdentity().equals("Merchant"))
                    cardNumber_not_merchant = false;

            if (!cardNumber_not_merchant)
                if (Const.masterShop_existed.containsKey(cardNumber))
                    if (!Const.masterShop_existed.get(cardNumber).isEmpty())
                        cardNumber_no_shop = false;

            if (permission_illegal) {
                return "Permission denied";
            } else if (cardNumber_illegal) {
                return "Illegal Kakafee number";
            } else if (cardNumber_not_existed) {
                return "Kakafee number not exists";
            } else if (cardNumber_not_merchant) {
                return "Kakafee number does not belong to a Merchant";
            } else if (cardNumber_no_shop) {
                return "Shop not exists";
            } else {
                Map<String, Shop> sortedShop = sortListShop(Const.masterShop_existed.get(cardNumber));
                for (Shop shop : sortedShop.values()) {
                    System.out.println(shop.getMaster().getCard_number() + " " + shop.getShopId() + " " + shop.getShopName());
                }
            }
        }
        return null;
    }

    String CancelShop(String[] cmd) {
        if (cmd.length != 2) {
            return "Illegal argument count";
        }
        String shopId = cmd[1];
        User current_user = Const.current_user;


        if (current_user == null) {
            return "Please log in first";
        }
        if (current_user.getIdentity().equals("Customer")) {
            return "Permission denied";
        }
        boolean shopId_illegal = !shopId.matches("S-[1-9]\\d*");
        boolean shopId_not_exist = true;
        if ((current_user.getIdentity().equals("Administrator") && Const.allShop_existed.containsKey(shopId)) || Const.allShop_existed.containsKey(shopId) && Const.allShop_existed.get(shopId).getMaster().equals(current_user)) {
            shopId_not_exist = false;
        }
        boolean order_not_process = false;
        for (Order order : Const.allOrder_existed.values()) {
            if (order.getCommodity().getShopId().equals(shopId)&&order.getOrderStatus()==0) {
                order_not_process = true;
                break;
            }
        }
        if (shopId_illegal) {
            return "Illegal shop id";
        } else if (shopId_not_exist) {
            return "Shop id not exists";
        } else if(order_not_process){
            return "Please process order for shop";
        }else {
            for (Commodity commodity : ((Map<String, Commodity>) Const.allShop_existed.get(shopId).getCommodities()).values()) {
                Const.allCommodities_existed.remove(shopId + commodity.getCommodityId());
            }
            Const.masterShop_existed.get(Const.allShop_existed.get(shopId).getMaster().getCard_number()).remove(shopId);
            Const.allShop_existed.remove(shopId);
            return "Cancel shop success";
        }

    }
}
